package com.qfedu.wfx.manager.configuration;

import com.qfedu.wfx.manager.realm.AccountRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class AppConfiguration {
    @Bean
    public DefaultWebSecurityManager provideSecurityManager(AccountRealm accountRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(accountRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean provideShiroFilter(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        //拦截的访问都跳转到login.html
        shiroFilterFactoryBean.setLoginUrl("/page/login.html");
        linkedHashMap.put("/page/login.html","anon");
        linkedHashMap.put("/user/login","anon");
        linkedHashMap.put("/js/**","anon");
        linkedHashMap.put("/css/**","anon");
        linkedHashMap.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 让shiro注解生效
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator provideDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        return autoProxyCreator;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor provideAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor sourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        sourceAdvisor.setSecurityManager(securityManager);
        return sourceAdvisor;
    }
}
